package com.example.jikeyoujikeyou.office_sz.service;

import com.alibaba.fastjson.JSONObject;
import com.example.jikeyoujikeyou.office_sz.model.HttpModel;
import com.example.jikeyoujikeyou.office_sz.model.base.BaseModel;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseService {

    public static OkHttpClient okHttpClient = new OkHttpClient();
    public static MediaType json = MediaType.parse("application/json;charset=utf-8");
    public static final String URL_PREFIX = "http://10.134.34.71:8080";

    /**
     * post方式提交数据
     *
     * @param url
     * @param baseModel
     */
    public static void postData(String url, BaseModel baseModel, final INetCallBack callBack) {
        HashMap map = baseModel.getAttrs();
        JSONObject jsonObject = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(json, jsonObject.toJSONString());
        final Request request = new Request.Builder().
                url(URL_PREFIX+url).post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onRequestFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                HttpModel httpModel = new HttpModel(str);
                switch (httpModel.getCode()) {
                    case HttpModel.REQUEST_SUCCESS:
                        callBack.onRequstSuccess(httpModel);
                        break;
                    default:
                        callBack.onRequestFail(httpModel.getMsg());
                        break;
                }
            }
        });

    }
}
